package com.zzl.springboot_mybatis_demo.aspect;

import com.gitee.yongzhuzl.commonutil.util.array.ArrayUtil;
import com.gitee.yongzhuzl.commonutil.util.empty.EmptyUtil;
import com.zzl.springboot_mybatis_demo.entity.user.User;
import com.zzl.springboot_mybatis_demo.exception.ResponseException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * description: @SetCreateTime注解切面
 * @author 朱正磊
 * @date 2019-09-04 09:52:32
 */
@Slf4j
@Aspect
@Component
public class SetCreateTimeAspect {

    /**
     * description: 定义注解的切点
     * @author 朱正磊
     * @date 2019-09-04 10:04:13
     */
    @Pointcut("@annotation(com.zzl.springboot_mybatis_demo.aspect.SetCreateTime)")
    public void pointcut() {}

    /**
     * description: 业务逻辑处理
     * @author 朱正磊
     * @date 2019-09-04 10:08:23
     * @param point 切点
     * @return 返回切点执行结果
     * @throws Throwable 异常
     */
    @Around("pointcut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        Object[] args = point.getArgs();
        log.info("【方法入参：{}】", ArrayUtil.array2String(args));

        if (EmptyUtil.isNotEmpty(args)) {
            if (args.length == 1 && args[0] instanceof User) {
                User user = (User) args[0];
                user.setCreateTime(new Date());
            } else {
                throw new ResponseException(400, "参数错误！");
            }
        } else {
            throw new ResponseException(400, "参数不能为空！");
        }

        Object result = point.proceed();
        log.info("【处理结果：{}】", result);
        return result;
    }

}
